import * as echarts from 'echarts';

type EChartsOption = echarts.EChartsOption;

var option: EChartsOption;
var myChart: any;

export const initLineBar = (barDataInfo, seriesName) => {
  // myChart ? myChart.clear() : ''
  if (myChart != null && myChart != '' && myChart != undefined) {
    myChart.dispose()
  }
  var chartDom = document.getElementById('bar-data-line')!;
  method(chartDom, barDataInfo, seriesName)
}

export const initSurfaceBar = (barDataInfo, seriesName) => {
  if (myChart != null && myChart != '' && myChart != undefined) {
    myChart.dispose()
  }
  var chartDom = document.getElementById('bar-data-surface')!;
  method(chartDom, barDataInfo, seriesName)
}

const method = (chartDom, barDataInfo, seriesName) => {
  myChart = echarts.init(chartDom);
  window.addEventListener('resize', function () {
    setTimeout(()=>{
      myChart.resize()
    }, 100)
  })
  option = getBar(barDataInfo, seriesName)
  option && myChart.setOption(option);
}

const getBar = (barInfo, seriesName) => {
  let xData = []
  let seriesData = []
  for (let i = 0; i < barInfo.length; i++) {
    xData.push(barInfo[i].category)
    seriesData.push(barInfo[i].measure)
    // seriesData.push(RemoveChinese(barInfo[i].measure))
  }

  let options = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xData,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: seriesName,
        type: 'bar',
        barWidth: '60%',
        data: seriesData,
        itemStyle: {
          normal: {
             //这里是重点
              color: function(params) {
                //注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
                var colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
                var index;
                //给大于颜色数量的柱体添加循环颜色的判断
                if (params.dataIndex >= colorList.length) {
                  index = params.dataIndex - colorList.length;
                  return colorList[index];
                }
                return colorList[params.dataIndex];
            }
          }
        }
      },
    ]
  }
  return options
}

// 去掉汉字
const RemoveChinese = (strValue) => {
  if (strValue != null && strValue != "") {
    var reg = /[\u4e00-\u9fa5]/g
    return strValue.replace(reg,'')
  } else {
    return ""
  }
}

// 提取汉字
const GetChinese = (strValue) => {
  if (strValue != null && strValue != "") {
    var reg = /[\u4e00-\u9fa5]/g
    return strValue.match(reg).join('')
  } else {
    return ""
  }
}
